/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.unice.miage.oobdoo.servlet;

import com.unice.miage.oobdoo.entity.Album;
import com.unice.miage.oobdoo.entity.Photo;
import com.unice.miage.oobdoo.entity.Utilisateur;
import com.unice.miage.oobdoo.enumeration.Statut;
import com.unice.miage.oobdoo.manager.AlbumManager;
import com.unice.miage.oobdoo.manager.UtilisateurManager;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Date;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author remi
 */
@WebServlet(name = "API", urlPatterns = {"/api"})
public class API extends HttpServlet {
    @EJB
    private AlbumManager albumManager;
    @EJB
    private UtilisateurManager utilisateurManager;
    
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        
            String action = request.getParameter("action");
            
            if (action != null)
            {
                if (action.equals("login")) {
                    response.setContentType("application/x-json");
                    String login = (String) request.getParameter("lg");
                    String pwd = (String) request.getParameter("pw");
                    
                    System.out.println("login : "+login);
                    System.out.println("password : "+pwd);
                    
                    if (utilisateurManager.acceptConnexion(login, pwd)) {

                        Utilisateur u = utilisateurManager.getUtilisateurByLogin(login);
                        Date d = new Date();
                        utilisateurManager.updateLastLogin(u, d.getTime());
                        
                        String uuid = u.getUniquekey();
                        
                        String ret = ("{\"ret\":{\"responseCode\":\"0\",\"uuid\":\""+uuid+"\"}}");
                        
                        boolean scriptTag = false;
                        String cb = request.getParameter("callback");
                        if (cb != null) {
                            scriptTag = true;
                            response.setContentType("text/javascript");
                        } else {
                            response.setContentType("application/x-json");
                        }
                        
                        if (scriptTag) {
                            out.write(cb + "(");
                        }
                        out.print(ret);
                        if (scriptTag) {
                            out.write(");");
                        }
                    } else {
                        out.print("{\"ret\":{\"responseCode\":\"1\",\"responseMsg\":\"Mauvais login/mot de passe\"}}");
                    }
                }else if(action.equals("sharedlist")){
                    
                    String login = (String) request.getParameter("lg");
                    String uuid = (String) request.getParameter("uuid");
                    
                    System.out.println("login : "+login);
                    System.out.println("uuid : "+uuid);
                    
                    String json = "{\"albums\":[]}";
                    Utilisateur u = utilisateurManager.getUtilisateurByUUID(uuid,login);
                    if(u instanceof Utilisateur)
                    {
                        Collection<Album> partage = u.getAlbumsPartagesValide();
                        json = "{\"albums\":[";
                        for(Album a: partage)
                        {
                            Collection<Photo> lstPhoto = a.getPhotos();
                            json += "{\"id\":\""+a.getId()+"\",\"name\":\""+a.getNom()+"\",";
                            json += "\"cover\":\"/upload/"+a.getAuteur().getId()+"/"+a.getId()+"/"+lstPhoto.iterator().next().getPathThumbHome()+"\",";
                            json += "\"owner\":\""+a.getAuteur().getLogin()+"\"},";
                        }
                        json = json.substring(0,json.length()-1);
                        json += "]}";
                    }
                    
                    boolean scriptTag = false;
                    String cb = request.getParameter("callback");
                    if (cb != null) {
                        scriptTag = true;
                        response.setContentType("text/javascript");
                    } else {
                        response.setContentType("application/x-json");
                    }

                    if (scriptTag) {
                        out.write(cb + "(");
                    }
                    out.print(json);
                    if (scriptTag) {
                        out.write(");");
                    }
                    
                }else if(action.equals("viewAlbum")){
                    
                    String login = (String) request.getParameter("lg");
                    String uuid = (String) request.getParameter("uuid");
                    String aid = (String) request.getParameter("aid");
                    
                    System.out.println("login : "+login);
                    System.out.println("uuid : "+uuid);
                    
                    String json = "{\"albums\":[]}";
                    Utilisateur u = utilisateurManager.getUtilisateurByUUID(uuid,login);
                    if(u instanceof Utilisateur)
                    {
                        Album a = albumManager.getAlbumById(Integer.parseInt(aid));
                        
                        System.out.println("album : "+a.getNom());
                        System.out.println("statut : "+a.getStatut());
                        json = "{\"photos\":[";
                        
                        if(albumManager.isAuthorizedToView(a, u))
                        {
                            for(Photo p : a.getPhotos())
                            {
                                json += "{";
                                
                                json += "\"id\":\""+p.getId()+"\",";
                                json += "\"name\":\""+p.getNom()+"\",";
                                json += "\"thumb\":\"/upload/"+a.getAuteur().getId()+"/"+a.getId()+"/"+p.getPathThumbHome()+"\",";
                                json += "\"full\":\"/upload/"+a.getAuteur().getId()+"/"+a.getId()+"/"+p.getPathThumbPhoto()+"\"";
                                json += "},";
                            }
                            json = json.substring(0,json.length()-1);
                        }
                        
                        json += "]}";
                    }
                    
                    boolean scriptTag = false;
                    String cb = request.getParameter("callback");
                    if (cb != null) {
                        scriptTag = true;
                        response.setContentType("text/javascript");
                    } else {
                        response.setContentType("application/x-json");
                    }

                    if (scriptTag) {
                        out.write(cb + "(");
                    }
                    out.print(json);
                    if (scriptTag) {
                        out.write(");");
                    }
                    
                }
            out.close();
            }
           }
   

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
